#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText

# python 2.3.*: email.Utils email.Encoders
from email.utils import COMMASPACE,formatdate
from email import encoders

import os
import socket
import fcntl
import struct
import time

local_ip_0 = ""
local_ip_1 = ""

#server['name'], server['user'], server['passwd']
def SendMail(server, from_addr, to_addr, subject, text, files=[]): 
  assert type(server) == dict
  assert type(to_addr) == list
  assert type(files) == list 

  msg = MIMEMultipart() 
  msg['From'] = from_addr 
  msg['Subject'] = subject 
  msg['To'] = COMMASPACE.join(to_addr) #COMMASPACE==', ' 
  msg['Date'] = formatdate(localtime=True) 
  msg.attach(MIMEText(text)) 
  
  for file in files: 
    part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data
    part.set_payload(open(file, 'rb'.read())) 
    encoders.encode_base64(part) 
    part.add_header(
        'Content-Disposition',
        'attachment; filename="%s"' % os.path.basename(file)) 
    msg.attach(part) 
  
  import smtplib 
  smtp = smtplib.SMTP(server['name']) 
  smtp.login(server['user'], server['passwd']) 
  smtp.sendmail(from_addr, to_addr, msg.as_string()) 
  smtp.close()

def GetLocalIp(ifname):
  try:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(
        fcntl.ioctl(
          s.fileno(),
          0x8915,  # SIOCGIFADDR
          struct.pack('256s', ifname[:15])
          )[20:24])
  except Exception,ex:
    return 'exception'

def SentLocalIpIfChanged():
  global local_ip_0
  global local_ip_1

  try:
    host_name = socket.gethostname()
    ip_0 = GetLocalIp('eth0')
    ip_1 = GetLocalIp('eth1')

    if ip_0 != local_ip_0 or ip_1 != local_ip_1:
      local_ip_0 = ip_0
      local_ip_1 = ip_1
      print("Ip changed: " + local_ip_0 + ", " + local_ip_1)

      server = {}
      server['name'] = 'smtp.163.com'
      server['user'] = 'sysulab623@163.com'
      server['passwd'] = 'lab623'
      SendMail(
          server,
          'sysulab623@163.com',
          ['lambda2fei@163.com'],
          host_name,
          local_ip_0 + ', ' + local_ip_1)
    # else:
      # print("Ip unchanged!")
  except Exception,ex:
    time.sleep(1)

if __name__ == "__main__":
  i_pow = 1;
  while 1:
    SentLocalIpIfChanged()
    time.sleep(60 * i_pow)
    if i_pow < 5:
      i_pow *= 2
